import { defineStore } from 'pinia'
import { getServers, createServer, updateServer, deleteServer } from '@/api/servers'
import { ElMessage } from 'element-plus'

export const useServersStore = defineStore('servers', {
  state: () => ({
    servers: [],
    currentServer: null,
    loading: false
  }),

  getters: {
    // 按分组组织服务器
    serversByGroup: (state) => {
      const groups = {}
      state.servers.forEach(server => {
        const group = server.group_name || 'default'
        if (!groups[group]) {
          groups[group] = []
        }
        groups[group].push(server)
      })
      return groups
    },

    // 服务器总数
    serverCount: (state) => state.servers.length
  },

  actions: {
    /**
     * 获取服务器列表
     */
    async fetchServers() {
      try {
        this.loading = true
        console.log('📋 获取服务器列表...')
        const res = await getServers()
        this.servers = res.data || []
        console.log('✅ 获取到', this.servers.length, '个服务器')
        return this.servers
      } catch (error) {
        console.error('❌ 获取服务器列表失败:', error)
        ElMessage.error('获取服务器列表失败')
        return []
      } finally {
        this.loading = false
      }
    },

    /**
     * 添加服务器
     */
    async addServer(serverData) {
      try {
        console.log('➕ 添加服务器...')
        const res = await createServer(serverData)
        ElMessage.success('服务器添加成功')
        await this.fetchServers()
        return res.data
      } catch (error) {
        console.error('❌ 添加服务器失败:', error)
        throw error
      }
    },

    /**
     * 更新服务器
     */
    async updateServerById(id, data) {
      try {
        console.log('✏️  更新服务器:', id)
        await updateServer(id, data)
        ElMessage.success('服务器更新成功')
        await this.fetchServers()
        return true
      } catch (error) {
        console.error('❌ 更新服务器失败:', error)
        throw error
      }
    },

    /**
     * 删除服务器
     */
    async removeServer(id) {
      try {
        console.log('🗑️  删除服务器:', id)
        await deleteServer(id)
        ElMessage.success('服务器删除成功')
        await this.fetchServers()
        return true
      } catch (error) {
        console.error('❌ 删除服务器失败:', error)
        throw error
      }
    },

    /**
     * 设置当前服务器
     */
    setCurrentServer(server) {
      this.currentServer = server
    }
  }
})

